// Copyright (c) 2025, 大连理工大学 (Dalian University of Technology)
//
// Licensed under the Mulan PSL v2.
// You can use this file according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of the License at
//
//     http://license.coscl.org.cn/MulanPSL2
//
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. SEE THE MULAN PSL v2
// FOR MORE DETAILS.

#include "Import/BDFImport/BulkData/Dynamic/FREQ5Parser.h"

#include <algorithm>
#include <cstdint>
#include <iostream>

#include "boost/algorithm/string.hpp"

#include "Utility/Logging/SGLogger.h"

#include "DBManager/DBServiceFactory.h"
#include "DBManager/IService/Input/Dynamic/IFREQ5Service.h"

#include "Import/BDFImport/BDFParserBase.h"

BULKDATA_ENTRY_PARSER_REG (FREQ5);

using namespace SG::DBManager;
using namespace SG::Import;
using namespace SG::DataStructure;

/*
// file://./../../Doc/MarkDown/BulkData/FREQ5/FREQ5.md>
*/

SG::DataStructure::Common::Status BDF::BULKDATA::ParseFREQ5 (const std::shared_ptr<SG::DBManager::DBServiceFactory>& dbServiceFactory,
                                                             std::vector<std::string>&                               dividedEntryInfo)
{
    SG::DataStructure::FEM::FREQ5Data tempData;

    // TODO(bug 001) 填写正确的 m_dominID 值，目前暂时设置为 1
    tempData.m_domainId = 1;
    tempData.m_F2       = 1.0E20;

    // 预分配内存以存储子集数据，避免后续动态扩展
    tempData.m_FRACTIONSList.reserve (dividedEntryInfo.size ());

    // 计算行数，每行包含 10 个字段
    size_t const rowNum = dividedEntryInfo.size () / 10;

    size_t beginColumnIndex;
    // 遍历每一行条目信息
    for (size_t curRow = 0; curRow < rowNum; curRow++)
    {
        if (curRow != 0)
        {
            beginColumnIndex = 1;
        }
        else
        {
            beginColumnIndex = 4;
        }
        // 遍历当前行的每一个字段，从第1列开始解析
        for (size_t fieldsColumn = beginColumnIndex; fieldsColumn < 9; fieldsColumn++)
        {
            // 获取当前字段的索引
            const size_t curIndex  = curRow * 10 + fieldsColumn;
            std::string& curStrKey = dividedEntryInfo[curIndex];

            // 判断当前字段是否为空，如果为空则跳过
            bool const isEmpty = is_all_space (curStrKey);
            if (isEmpty)
            {
                continue;
            }

            tempData.m_sId = convertToI64 (dividedEntryInfo[1]);
            tempData.m_F1  = convertToReal (dividedEntryInfo[2]);
            tempData.m_F2  = convertToReal (dividedEntryInfo[3]);
            // 如果字段不为空，将其转换为 long long 类型并存储到 m_subSets 中
            tempData.m_FRACTIONSList.emplace_back (FEM::FREQ5Data::FRACTIONSData{ convertToReal (curStrKey) });
        }
    }

    // 将解析出来的数据添加到数据库中，并返回结果
    return dbServiceFactory->get<IFREQ5Service> ()->Add (tempData);
}